#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import logging
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cloudstudio.v20230508 import cloudstudio_client, models

class CloudAPI:
    """腾讯云API调用封装类"""
    
    def __init__(self, secret_id, secret_key, region="ap-guangzhou"):
        """
        初始化API客户端
        
        Args:
            secret_id: 腾讯云 SecretId
            secret_key: 腾讯云 SecretKey 
            region: 地域，默认为广州
        """
        self.logger = logging.getLogger(__name__)
        
        try:
            cred = credential.Credential(secret_id, secret_key)
            http_profile = HttpProfile()
            http_profile.endpoint = "cloudstudio.tencentcloudapi.com"
            
            client_profile = ClientProfile()
            client_profile.httpProfile = http_profile
            
            self.client = cloudstudio_client.CloudstudioClient(cred, region, client_profile)
            
        except TencentCloudSDKException as err:
            self.logger.error(f"Failed to initialize cloud API client: {err}")
            raise
            
    def get_workspaces(self):
        """
        获取工作空间列表
        
        Returns:
            list: 工作空间列表
        """
        try:
            req = models.DescribeWorkspacesRequest()
            resp = self.client.DescribeWorkspaces(req)
            return resp.Data
            
        except TencentCloudSDKException as err:
            self.logger.error(f"Failed to get workspaces: {err}")
            raise
            
    def run_workspace(self, space_key):
        """
        启动工作空间
        
        Args:
            space_key: 工作空间标识
            
        Returns:
            bool: 是否启动成功
        """
        try:
            req = models.RunWorkspaceRequest()
            req.SpaceKey = space_key
            self.client.RunWorkspace(req)
            self.logger.info(f"Successfully started workspace: {space_key}")
            return True
            
        except TencentCloudSDKException as err:
            self.logger.error(f"Failed to start workspace {space_key}: {err}")
            return False 